const { ipcRenderer } = require("electron");
const fse = require("fs-extra");
const path = require("path");
const {
	cmdOpenTool,
	cmdLogin,
	cmdPreview,
	cmdUpload,
	cmdClose,
} = require("../util/xcx_cmd");
const config = require("../../config");
window.onload = function() {
	console.log(process);
	let projectRoot = "F:\\wx-workspace\\beautiful-table-mini";
	let openFolder = document.querySelector("#open-folder");
	let xcxPreview = document.querySelector("#xcx-preview");
	let xcxUpload = document.querySelector("#xcx-upload");
	let xcxLogin = document.querySelector("#xcx-login");
	openFolder.onclick = e => {
		try {
			ipcRenderer.send("open-directory-dialog");
		} catch (error) {
			console.log(error);
		}
	};
	xcxLogin.onclick = async () => {
		try {
			const qrcode = await xcxLoginFn();
			showQrcode(qrcode);
		} catch (error) {
			console.log(error);
		}
	};
	xcxPreview.onclick = () => {
		try {
			const qrcode = xcxPreviewFn(projectRoot);
			showQrcode(qrcode);
		} catch (error) {
			console.log(error);
		}
	};
	xcxUpload.onclick = () => {
		try {
			xcxUploadFn({
				version: "1.0.1",
				project_root: projectRoot,
				desc: "aa",
			});
		} catch (error) {
			console.log(error);
		}
	};
	ipcRenderer.on("xcx-select-folder", (event, file) => {
		try {
			const project_root = file[0];
			projectRoot = project_root;
			const { stdout } = cmdOpenTool(project_root);
			showExeMessage(stdout);
		} catch (error) {
			console.log(error);
		}
	});
	async function xcxLoginFn() {
		await cmdLogin();
		let qrcode = readFile(config.loginTmp);
		return qrcode;
	}
	/**
	 * 小程序预览
	 * @param {*} projectRoot
	 */
	function xcxPreviewFn(projectRoot) {
		if (projectRoot) {
			cmdPreview({
				project_root: projectRoot,
			});
			let qrcode = readFile(config.previewTmp);
			qrcode = `data:image/png;base64,${qrcode}`;
			return qrcode;
		} else {
			throw "project_root为空";
		}
	}
	/**
	 * 小程序上传
	 * @param {*} param0
	 */
	function xcxUploadFn({ version = "1.0.1", project_root = "", desc = "" }) {
		if (!project_root) {
			throw "project_root 为空";
		}
		const result = cmdUpload({
			version,
			project_root,
			desc,
		});
		return result;
	}
	/**
	 * 读取文件
	 * @param {*} fileDir
	 */
	function readFile(fileDir = ``) {
		return fse.readFileSync(fileDir);
	}
	/**
	 * 展示二维码
	 * @param {*} src
	 */
	function showQrcode(src = ``) {
		document.querySelector(".qrcode img").setAttribute("src", src);
	}
	/**
	 * 展示命令行信息
	 * @param {*} msg
	 */
	function showExeMessage(msg = "") {
		document.querySelector(".show-exex-message").innerHTML = msg;
	}
};
